package com.atguigu.gulimall.third.controller;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.exception.BizCodeEnum;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.third.service.SmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@Api(tags = "阿里云短信服务")
public class SmsController {
    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @ApiOperation("获取短信验证码")
    @GetMapping(value = "/send/{phone}")
    public R code(@PathVariable String phone) {
        String code = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone);
        System.out.println(code);
        //TODO 接口防刷
        if (!StringUtils.isEmpty(code)){
            long l = Long.parseLong(code.split("_")[1]);
            if(System.currentTimeMillis()-l<60000){
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(),BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }
//        code = RandomUtil.getFourBitRandom();
        Map<String, Object> param = new HashMap<>();
        String code1= UUID.randomUUID().toString().substring(0,5);
        param.put("code", code1);
        boolean isSend = smsService.send(phone, "SMS_133261141", param);
        System.out.println(isSend);

        if (isSend) {
            redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX+phone,
                    code1+"_"+System.currentTimeMillis(), 1, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error("发送短信失败");
        }
    }
}
